package com.landeb.shop.huo.act;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.support.v4.view.LayoutInflaterCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.landeb.shop.R;
import com.landeb.shop.huo.MyApplication;
import com.landeb.shop.huo.adapter.DialogListAdapter;
import com.landeb.shop.huo.bean.BeanActCreateOrder;
import com.landeb.shop.huo.bean.BeanActCreateOrderResult;
import com.landeb.shop.huo.bean.BeanCoupon;
import com.landeb.shop.huo.httpRequest.ActAddressSelectRequest;
import com.landeb.shop.huo.httpRequest.ActCreateOrderRequest;
import com.landeb.shop.huo.view.FixedGridView;

import java.util.ArrayList;
import java.util.List;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class CreateOrderActivity extends BaseActivity implements View.OnClickListener {


    private LinearLayout btnBack, llAddress, llInvoice, llCoupon;
    private TextView tvName, tvPhoneNum, tvAddress, tvShopName, tvInvoiceMsg, tvPrice, tvCouponMsg;
    private Button btnCreateOrder;
    private FixedGridView mGridView;
    private SwipeRefreshLayout mSRL;
    private static final int GET_ADDRESS = 123;
    private static final int GET_INVOICE = 321;
    private OkHttpClient client;

    public static final int FLAG_COACT = 111;

    private Retrofit mRetrofit;
    private String mUrl;
    private ActCreateOrderRequest mRequest;
    private boolean isRefreshing = false;

    private String selectedId;
    private int needInvoice = 2;
    private String addressId;
    private String mInvoiceName;
    private String mInvoiceType;
    private String mInvoiceTypeCode;
    private String mInvoiceMsg;
    private String orderId;

    private List<BeanCoupon.DataBean> mCouponList = new ArrayList<>();
    private boolean canShowDialog;
    private String couponOption="";

    public static void toAct(Context context) {
        Intent intent = new Intent(context, CreateOrderActivity.class);
        context.startActivity(intent);
    }

    public static void toAct(Context context, String selectedId) {
        Intent intent = new Intent(context, CreateOrderActivity.class);
        intent.putExtra("selectedId", selectedId);

        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create_order);

        Intent intent = getIntent();
        selectedId = intent.getStringExtra("selectedId");

        Log.e("onCreate: ", "selectedId++++++++" + selectedId);

        client = MyApplication.getClient();
        mUrl = MyApplication.BASE_URL;
        mRetrofit = new Retrofit.Builder()
                .baseUrl(mUrl)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .client(client)
                .build();
        mRequest = mRetrofit.create(ActCreateOrderRequest.class);

        initView();
        initData();
        initEvent();

        refresh();
    }

    private void refresh() {

        if (!isRefreshing) {

            isRefreshing = true;
            mSRL.setRefreshing(true);

            mRequest.getOrder()
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Subscriber<BeanActCreateOrder>() {
                        @Override
                        public void onCompleted() {
                            Log.e("getOrder", "onCompleted: ");
                            isRefreshing = false;
                            mSRL.setRefreshing(false);
                        }

                        @Override
                        public void onError(Throwable e) {
                            Log.e("getOrder", "onError: " + e.toString());
                            isRefreshing = false;
                            mSRL.setRefreshing(false);
                        }

                        @Override
                        public void onNext(BeanActCreateOrder beanActCreateOrder) {

                            if (beanActCreateOrder.getStatus() == 1) {

                                tvName.setText(beanActCreateOrder.getData().getAddress().getRealname());
                                tvPhoneNum.setText(beanActCreateOrder.getData().getAddress().getMobile());
                                tvAddress.setText(beanActCreateOrder.getData().getAddress().getProvince()
                                        + beanActCreateOrder.getData().getAddress().getCity()
                                        + beanActCreateOrder.getData().getAddress().getCountry()
                                        + beanActCreateOrder.getData().getAddress().getTown()
                                        + beanActCreateOrder.getData().getAddress().getAddress());

                                addressId = beanActCreateOrder.getData().getAddress().getId();

                                tvPrice.setText("共计：¥" + beanActCreateOrder.getData().getMoney());

                                getCoupon(beanActCreateOrder.getData().getMoney());



                            } else {
                                Toast.makeText(CreateOrderActivity.this, beanActCreateOrder.getInfo(), Toast.LENGTH_SHORT).show();
                            }

                        }
                    });

        }


    }

    private void initEvent() {

        mSRL.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refresh();
            }
        });

        btnBack.setOnClickListener(this);
        llAddress.setOnClickListener(this);
        llInvoice.setOnClickListener(this);
        btnCreateOrder.setOnClickListener(this);

        llCoupon.setOnClickListener(this);
    }

    private void initData() {

    }

    private void initView() {

        mGridView = (FixedGridView) findViewById(R.id.act_create_order_GV);
        mSRL = (SwipeRefreshLayout) findViewById(R.id.act_create_order_srl);
        mSRL.setColorSchemeColors(getResources().getColor(R.color.colorPrimary));
        mSRL.setEnabled(false);

        btnBack = (LinearLayout) findViewById(R.id.act_create_order_btn_back);
        llAddress = (LinearLayout) findViewById(R.id.act_create_order_ll_address);
        llInvoice = (LinearLayout) findViewById(R.id.act_create_order_LL_invoice);

        tvName = (TextView) findViewById(R.id.act_create_order_tv_name);
        tvPhoneNum = (TextView) findViewById(R.id.act_create_order_tv_phoneNum);
        tvAddress = (TextView) findViewById(R.id.act_create_order_tv_address);
        tvShopName = (TextView) findViewById(R.id.act_create_order_tv_shopName);
        tvInvoiceMsg = (TextView) findViewById(R.id.act_create_order_tv_invoiceMsg);
        tvPrice = (TextView) findViewById(R.id.act_create_order_tv_price);

        tvCouponMsg = (TextView) findViewById(R.id.act_create_order_tv_couponMsg);

        btnCreateOrder = (Button) findViewById(R.id.act_create_order_btn_create);

        llCoupon = (LinearLayout) findViewById(R.id.act_create_order_ll_coupon);
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {

            case R.id.act_create_order_btn_back:
                // TODO: 2016/11/29 返回键
                onBackPressed();
                break;

            case R.id.act_create_order_ll_address:
                // TODO: 2016/11/29 地址选择
//                AddressSelectActivity.toAct(CreateOrderActivity.this);

                Intent addressIntent = new Intent(CreateOrderActivity.this, AddressSelectActivity.class);
                addressIntent.putExtra("flag", CreateOrderActivity.FLAG_COACT);
                startActivityForResult(addressIntent, GET_ADDRESS);

                break;

            case R.id.act_create_order_LL_invoice:
                // TODO: 2016/11/29 发票编辑
                Intent invoiceIntent = new Intent(CreateOrderActivity.this, InvoiceEditActivity.class);
                startActivityForResult(invoiceIntent, GET_INVOICE);
                break;

            case R.id.act_create_order_btn_create:
                // TODO: 2016/11/29 生成订单

                final ProgressDialog dialog = new ProgressDialog(this);
                dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
                dialog.setMessage("正在提交，请稍后");
                dialog.setCancelable(false);
                dialog.show();

                mRequest.createOrder(selectedId, addressId, needInvoice, mInvoiceTypeCode, mInvoiceName, mInvoiceMsg)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Subscriber<BeanActCreateOrderResult>() {
                            @Override
                            public void onCompleted() {
                                Log.e("createOrder", "onCompleted: ");
                                dialog.dismiss();
                            }

                            @Override
                            public void onError(Throwable e) {
                                Log.e("createOrder", "onError: " + e.toString());
                                dialog.dismiss();
                            }

                            @Override
                            public void onNext(BeanActCreateOrderResult beanActCreateOrderResult) {

                                if (beanActCreateOrderResult.getStatus() == 1) {

                                    orderId = beanActCreateOrderResult.getData().getId();

                                    PayActivity.toAct(CreateOrderActivity.this, orderId);

                                    finish();

                                } else {
                                    Toast.makeText(CreateOrderActivity.this, beanActCreateOrderResult.getInfo(), Toast.LENGTH_SHORT).show();
                                }

                            }
                        });

                break;

            case R.id.act_create_order_ll_coupon:

                if (canShowDialog) {

                    showDialog();
                }


                break;

        }

    }

    private void showDialog() {

        View contentView = LayoutInflater.from(this).inflate(R.layout.dialog_coupon_list, null);
        ListView contentList = (ListView) contentView.findViewById(R.id.contentList);
        DialogListAdapter contentAdapter = new DialogListAdapter(mCouponList, this);
        contentList.setAdapter(contentAdapter);
        contentList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                couponOption=mCouponList.get(position).getMark();

            }
        });

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setView(contentView)
                .setTitle("请选择优惠券")
                .setCancelable(true)
                .create().show();
    }

    private void getCoupon(String money) {

        mRequest.getCoupon(money)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new Subscriber<BeanCoupon>() {
                    @Override
                    public void onCompleted() {
                        Log.e("coupon: ","onCompleted" );

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(BeanCoupon beanCoupon) {

                        if (beanCoupon.getStatus() == 1) {


                            mCouponList.clear();
                            mCouponList.addAll(beanCoupon.getData());

                            Log.e("coupon: ",mCouponList.size()+"" );

                            canShowDialog=true;

                        } else {

                            tvCouponMsg.setText(beanCoupon.getInfo());

                            canShowDialog=false;
                        }


                    }
                });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.e("onActivityResult: ", requestCode + "+++++" + resultCode + "++++");

        if (requestCode == GET_ADDRESS && resultCode == RESULT_OK) {
// TODO: 2016/11/30 地址回调
            String name = data.getStringExtra("name");
            String phoneNum = data.getStringExtra("phoneNum");
            String address = data.getStringExtra("address");

            addressId = data.getStringExtra("id");

            tvName.setText(name);
            tvPhoneNum.setText(phoneNum);
            tvAddress.setText(address);
        }

        if (requestCode == GET_INVOICE && resultCode == RESULT_OK) {
            // TODO: 2016/11/29 发票回调

            needInvoice = 1;

            mInvoiceType = data.getStringExtra("type");
            mInvoiceName = data.getStringExtra("name");
            mInvoiceMsg = data.getStringExtra("msg");

            if (mInvoiceType.equals("个人")) {
                mInvoiceTypeCode = "person";
            } else if (mInvoiceType.equals("单位")) {
                mInvoiceTypeCode = "company";
            }

            tvInvoiceMsg.setText(mInvoiceType + "-" + mInvoiceName + "-" + mInvoiceMsg);

        }

        if (requestCode == GET_INVOICE && resultCode == RESULT_CANCELED) {

            needInvoice = 2;
            tvInvoiceMsg.setText("不开发票");


        }

    }
}
